package com.xzzz.backend.bsms.server.rbac.menu;


import cn.hutool.core.collection.CollUtil;
import com.xzzz.common.base.util.BeanUtil;
import com.xzzz.backend.bsms.server.rbac.menu.pojo.MenuEntity;
import com.xzzz.backend.bsms.server.rbac.menu.pojo.MenuTreeRes;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xzzz
 * 
 */
public class MenuTreeUtil {

    private MenuTreeUtil() {

    }

    /**
     * 即一次菜单的父ID
     */
    private static final Long ROOT_MENU_ID = 0L;

    /**
     * 将菜单列表构造成树状
     * @param list 菜单列表
     * @return 树状菜单对象
     */
    public static List<MenuTreeRes> treeWrap(List<MenuEntity> list) {
        final List<MenuTreeRes> allList = BeanUtil.toList(list, MenuTreeRes.class);
        //查询根菜单
        List<MenuTreeRes> rootLevel =
                allList.stream()
                        .filter(p -> p.getParentId().equals(ROOT_MENU_ID))
                        .sorted(Comparator.comparing(MenuTreeRes::getSort))
                        .collect(Collectors.toList());
        rootLevel.parallelStream().forEach(item -> setChild(item, allList));
        return rootLevel;
    }

    private static void setChild(MenuTreeRes p, List<MenuTreeRes> allMenu) {
        //将集合中自己去除
        List<MenuTreeRes> child = allMenu.parallelStream()
                .filter(a -> a.getParentId().equals(p.getId()))
                .sorted(Comparator.comparing(MenuTreeRes::getSort))
                .collect(Collectors.toList());
        //如果集合不为空
        if (!CollUtil.isEmpty(child)) {
            p.setChildren(child);
            //递归设置子元素，多级菜单支持
            child.parallelStream().forEach(c -> setChild(c, allMenu));
        }
    }
}
